package com.malbbmsomanager;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.malbbmsomanager.R;


public class DM_BBM_InvoiceMainActivity extends Activity {
	private static final String TAG = null;
	private String DBNAME = "dminvoicemanagerbbm.db";
	private String USER_SETTINGS = "usersettings";
	private String TEMP_REP_INVOICESUMERY = "frepInvoiceSumery";
	private String ITEM_AREA = "fArea";
	private String ITEM_COMPANY_SETTING = "fCompanySetting";
	// private String ITEM_CONTROL = "fControl";
	private String ITEM_DEBTOR = "fDebtor";
	private String ITEM_LOC_DETAILS = "fItemLoc";
	private String ITEM_LOCATION = "fLocation";
	private String ITEM_PRICE = "fItemPri";
	private String ITEMS = "fItems";
	private String INV_DETAILS = "FinvDet";
	private String INV_HEADER = "FinvHed";
	private String INV_NUMBER = "InvNumber";
	private String INV_SAL_REP = "fSalRep";
	private String SERVER_DETAILS = "serverinfo";

	private SQLiteDatabase mydb;
	String RepInvCode, TransTypePrefix, AgentPrefixType, LatestInvNumber,
			LatestInvState, ActiveInvoice, RepPrefixCode, RepLocationCode= "000",
			username, userpass, RepAreaCode, connectionURL;
	EditText ETusername, ETpassword;
	int TAGCHECKURL = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_bbm_invoice_main_activity);

		ETusername = (EditText) findViewById(R.id.repuname);
		ETpassword = (EditText) findViewById(R.id.reppsswd);

		checkUrlConfigurations();

		Button userLogin = (Button) findViewById(R.id.userloginbutton);
		userLogin.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (ETusername.length() != 0 && ETpassword.length() != 0) {
					username = ETusername.getText().toString().toUpperCase();
					userpass = ETpassword.getText().toString();
					if (username.equals("FINACBBM")
							&& userpass.equals("FINAC@BBM")) {
						if (TAGCHECKURL == 200) {
							Intent myIntent = new Intent(view.getContext(),
									DM_BBM_Settings.class);
							myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
									| Intent.FLAG_ACTIVITY_NEW_TASK);
							myIntent.putExtra("TAGID", "SUPPER");
							startActivityForResult(myIntent, 0);
							finish();
							return;
						} else if (TAGCHECKURL == 0) {
							Intent myIntent = new Intent(view.getContext(),
									DM_BBM_Properties.class);
							myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
									| Intent.FLAG_ACTIVITY_NEW_TASK);
							startActivityForResult(myIntent, 0);
							finish();
							return;
						}

					} else {
						// agentPrefix();
						// repLocation();
						repPrefix();
						authenticateuser(username.toUpperCase(),
								userpass.toUpperCase());
					}
				} else {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_BBM_InvoiceMainActivity.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("Invalid Login");
					// Setting Dialog Message
					alertDialog.setMessage("Enter User Name & Password");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
				}
			}

		});

		Button quitall = (Button) findViewById(R.id.quitall);
		quitall.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				DM_BBM_InvoiceMainActivity.this.finish();
				finish();
				android.os.Process.killProcess(android.os.Process.myPid());

			}

		});
		super.onDestroy();
	}

	private void checkUrlConfigurations() {
		// TODO Auto-generated method stub
		Cursor getserverurl = null;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			getserverurl = mydb.query(SERVER_DETAILS, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}
		if (getserverurl != null) {
			if (getserverurl.getCount() > 0) {
				while (getserverurl.moveToNext()) {
					connectionURL = getserverurl.getString(1);
					TAGCHECKURL = 200;
					Log.v(TAG, "connectionURL:" + connectionURL);
				}
			} else {
				TAGCHECKURL = 0;
			}
		}
		mydb.close();
	}

	private void authenticateuser(String username, String userpass) {
		SQLiteDatabase mydb = openOrCreateDatabase(DBNAME,
				Context.MODE_PRIVATE, null);
		Cursor replogincursor = null;
		String[] cols = { "RepCode", "RepTCode", "AreaCode" };
		try {
			String querySalRep = "SELECT RepCode,RepName,RepIdNo FROM fSalRep Where  RepCode ='"
					+ username + "' AND RepCode ='" + userpass + "'";
			replogincursor = mydb.rawQuery(querySalRep, null);
		} catch (Exception e) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_BBM_InvoiceMainActivity.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("Invalid User");
			// Setting Dialog Message
			alertDialog.setMessage("Invalid User Name & Password");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			mydb.close();
			return;
		}
		if (replogincursor != null) {
			if (replogincursor.getCount() > 0) {
				while (replogincursor.moveToNext()) {
					RepAreaCode = replogincursor.getString(2);
				}
			}
		}

		if (replogincursor == null) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_BBM_InvoiceMainActivity.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("Invalid User");
			// Setting Dialog Message
			alertDialog.setMessage("Invalid User Name & Password");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			mydb.close();
			return;

		}
		if (replogincursor.getCount() < 1) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_BBM_InvoiceMainActivity.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("Invalid User");
			// Setting Dialog Message
			alertDialog.setMessage("Invalid User Name & Password");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			replogincursor.close();
			mydb.close();
			return;
		}

		if (replogincursor.getCount() == 1) {
			// Success Loin Activity
			// RepAreaCode = replogincursor.getString(2);
			UpdateUserSettings();
			Intent myIntent = new Intent(this, DM_BBM_InvoiceMenu.class);
			// myIntent.putExtra("TAGID", "SALES");
			startActivityForResult(myIntent, 0);
		} else {
			replogincursor.close();
			mydb.close();
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_BBM_InvoiceMainActivity.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("Login Error");
			// Setting Dialog Message
			alertDialog.setMessage("Error User Login");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);

		}

	}

	/*
	 * private void repLocation() { // TODO Auto-generated method stub
	 * SQLiteDatabase mydb; mydb = openOrCreateDatabase(DBNAME,
	 * Context.MODE_PRIVATE, null); String currentUser =
	 * username.toUpperCase().trim(); Cursor selectrepLocation = null;
	 * 
	 * try { selectrepLocation = mydb.query(ITEM_LOCATION, null, "RepCode='" +
	 * currentUser + "'", null, null, null, null); } catch (Exception e) { }
	 * 
	 * if (selectrepLocation != null) { if (selectrepLocation.getCount() > 0) {
	 * while (selectrepLocation.moveToNext()) { String user =
	 * selectrepLocation.getString(13); RepLocationCode =
	 * selectrepLocation.getString(9); } } }
	 * 
	 * selectrepLocation.close(); mydb.close(); }
	 */
	/*
	 * protected void agentPrefix() { // TODO Auto-generated method stub
	 * SQLiteDatabase mydb; mydb = openOrCreateDatabase(DBNAME,
	 * Context.MODE_PRIVATE, null); Cursor selectAgentPreType = null;
	 * 
	 * try { selectAgentPreType = mydb.query(ITEM_CONTROL, null, null, null,
	 * null, null, null); } catch (Exception e) { } if (selectAgentPreType !=
	 * null) { if (selectAgentPreType.getCount() > 0) { while
	 * (selectAgentPreType.moveToNext()) { AgentPrefixType =
	 * selectAgentPreType.getString(18); }
	 * 
	 * } } selectAgentPreType.close(); mydb.close(); }
	 */

	private void repPrefix() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectRepPrefix = null;

		try {

			selectRepPrefix = mydb.query(INV_SAL_REP, null, "RepCode ='"
					+ username.toUpperCase().trim() + "'", null, null, null,
					null);

		} catch (Exception e) {
		}
		if (selectRepPrefix != null) {
			if (selectRepPrefix.getCount() > 0) {
				while (selectRepPrefix.moveToNext()) {
					RepPrefixCode = selectRepPrefix.getString(14);
					if(RepPrefixCode.trim()  != null){
						RepPrefixCode = selectRepPrefix.getString(14);
						Log.v(TAG, "PRINT REF PREFIX 1:" + RepPrefixCode);
						if(RepPrefixCode.equals("null")){
							RepPrefixCode = "A";
							Log.v(TAG, "PRINT REF PREFIX 2:" + RepPrefixCode);
						}
					}
					
					else {
						RepPrefixCode = "A";
						Log.v(TAG, "PRINT REF PREFIX 3:" + RepPrefixCode);
					}
					Log.v(TAG, "RepPrefixCode :" + RepPrefixCode);
				}

			}
		}

		selectRepPrefix.close();
		mydb.close();
	}

	// ****Udate Current Login User**********
	private void UpdateUserSettings() {
		// TODO Auto-generated method stub
		Log.v(TAG, "UpdateUserSettings Call");
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curUdateUserSetting = null;
		try {
			curUdateUserSetting = mydb.query(USER_SETTINGS, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (curUdateUserSetting != null) {
			if (curUdateUserSetting.getCount() > 0) {
				while (curUdateUserSetting.moveToNext()) {
					String CurrentUserId = curUdateUserSetting.getString(0);
					String CurrentUser = curUdateUserSetting.getString(1);
					String LoginUser = ETusername.getText().toString()
							.toUpperCase();

					if (CurrentUser.equals(LoginUser)) {

					} else {
						ContentValues user = new ContentValues();
						user.put("username", ETusername.getText().toString().toUpperCase());
						user.put("lrepprefix", RepPrefixCode);
						user.put("lreploccode", RepAreaCode);
						user.put("locationCode", RepAreaCode);
						user.put("repareacode", RepAreaCode);
						mydb.update(USER_SETTINGS, user, "_id ='"
								+ CurrentUserId + "'", null);
					}

				}
			}
		}
	}

	private String getCurrentTimeString() {
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("dd/MM/yyyy");
		String date_to_string = ddMMMyyFormat.format(dateNow);
		return date_to_string;
	}

	/*@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.dm_bbm_app_main_loading, menu);
		return true;
	}*/

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			alertDialog();
			// Do Code Here
			// If want to block just return false
			return false;
		}
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			alertDialog();
			// Do Code Here
			// If want to block just return false
			return false;
		}
		if (keyCode == KeyEvent.KEYCODE_HOME) {
			Intent i = new Intent(Intent.ACTION_MAIN);
			i.addCategory(Intent.CATEGORY_HOME);
			startActivity(i);
			alertDialog();
			// Do Code Here
			// If want to block just return false
			return false;
		}
		if (keyCode == KeyEvent.KEYCODE_SEARCH) {
			alertDialog();
			// Do Code Here
			// If want to block just return false
			return false;
		}
		if (keyCode == KeyEvent.KEYCODE_SETTINGS) {
			alertDialog();
			// Do Code Here
			// If want to block just return false
			return false;
		}

		return super.onKeyDown(keyCode, event);
	}

	private void alertDialog() {
		// TODO Auto-generated method stub
		final AlertDialog alertDialog = new AlertDialog.Builder(
				DM_BBM_InvoiceMainActivity.this).create();
		// Setting Dialog Title
		alertDialog.setTitle("HOME PRESSED");
		// Setting Dialog Message
		alertDialog.setMessage("HOME PRESSED..");
		// Setting Icon to Dialog
		alertDialog.setIcon(R.drawable.warning);
		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				alertDialog.dismiss();
			}
		});
		// Showing Alert Message
		alertDialog.show();
		alertDialog.setCanceledOnTouchOutside(false);
	}
	
	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}
}
